#include "FileUtil.hpp"
#include <iostream>

namespace Utility {

FilePhaser &FilePhaser::GetInstance() {
  static FilePhaser phaser;
  return phaser;
}

template <typename T, typename Enable>
bool FilePhaser::GetContents(const std::string &fileName, T *buf) {
  FileBufferAdaptor<T> adaptor(buf);
  return GetContents(fileName, &adaptor);
}

bool FilePhaser::GetContents(const std::string &fileName, IFileBuffer *buf) {
  if (fileName.empty()) {
    return false;
  }
  std::fstream file;
  file.exceptions(std::ios::eofbit | std::ios::goodbit | std::ios::failbit);
  try {
    file.open(fileName, std::ios::in | std::ios::binary);
    file.seekg(0, file.end);
    auto size = file.tellg();
    file.seekg(0, file.beg);
    buf->resize(size);
    file.read(reinterpret_cast<char *>(buf->buffer()), size);
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
    file.close();
    return false;
  }
  file.close();
  return true;
}

std::string FilePhaser::GetStringFromFile(const std::string &fileName) {
  std::string s;
  GetContents(fileName, &s);
  return s;
}

} // namespace Utility